package com.xiu.travel.security.pojo;

import com.alibaba.fastjson2.annotation.JSONField;
import com.xiu.travel.entity.UmsMember;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 登录用户信息
 *
 * @author yingyingying
 * @date 2023/3/13 20:50
 */
@Data
@NoArgsConstructor
@Accessors(chain = true)
public class SecurityUser implements UserDetails {
    private Long id;

    /**
     * 用户名
     */
    private String username;
    /**
     * 用户密码
     */
    private String password;
    /**
     * 用户状态
     */
    private Boolean enabled;

    private List<String> permissions;
    private List<String> roles;

    @JSONField(serialize = false)
    private List<SimpleGrantedAuthority> authorities;

    public SecurityUser(UmsMember umsMember, List<String> permissions, List<String> roles) {
        this.id = umsMember.getId();
        this.username = umsMember.getUsername();
        this.password = umsMember.getPassword();
        this.enabled = true;
        this.permissions = permissions;
        this.roles = roles;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorities != null) {
            return authorities;
        }
        authorities = permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        return authorities;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
